package com.imau.common.handler;

import com.alibaba.fastjson.JSON;
import com.imau.common.entiry.ResultCode;
import com.imau.common.entiry.ResultEntity;
import com.imau.common.exception.CommonException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/baseExceptionHandler")
public class BaseExceptionHandler extends HttpServlet
{


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取异常对象
        Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
        //2. 判断是自定义异常

        ResultEntity error = this.errorHandeler(request,response,throwable);
        String strJson = JSON.toJSONString(error);
        response.getWriter().write(strJson);



    }

    private ResultEntity errorHandeler(HttpServletRequest request, HttpServletResponse response, Throwable e) {

        if(e.getClass() == CommonException.class)
        {
            //类型转型
            CommonException ce = (CommonException) e;
            ResultEntity result = new ResultEntity(ce.getResultCode());
            return result;

        }else{

            ResultEntity result = new ResultEntity(ResultCode.SERVER_ERROR);
            return result;
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
